package com.xian;

import com.alibaba.fastjson.JSON;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 获取apollo信息
 * @author jemson
 */
public class GetApolloInfo {
    public static void main(String[] args) {

        //参数顺序 0-apollo.meta  1-app.id  2-namespace  3-cluster 4-env  5-apollo.cacheDir
        //http://172.18.6.1:8080 orderService application bigdata DEV /root/test/apolloCacheDir
        System.out.println("可以传入5个参数,顺序为:0-apollo.meta  1-app.id  2-namespace  3-cluster 4-env  5-apollo.cacheDir");



        String namespace = init(args);
        Config config = ConfigService.getConfig(namespace);

        //获取所有key
        Map<String, String> map = new HashMap<String, String>(); //存放kv值
        Set<String> keys = config.getPropertyNames();
        for (String key : keys) {
           String value = config.getProperty(key, "");
           //System.out.println(key + "===" + value);
           map.put(key, value);
        }


        String resultJson = JSON.toJSONString(map);
        //必须要打印出去，shell客户端才获取得了
        System.out.println(resultJson);




    }

    /**
     * 初始化apollo
     */
    private static String init(String[] args) {
        if(args==null || args.length<3) {
            /*
            参数顺序 0-apollo.meta  1-app.id  2-namespace  3-cluster 4-env  5-apollo.cacheDir
             */
            System.err.println("请传入apollo修改配置信息: 参数顺序 0-apollo.meta  1-app.id  2-namespace  3-cluster");
            System.err.println("http://172.18.x.x:8080 orderService wsShunFengChe.mysql");
            System.exit(1);
        }

        String namespace = "";
        for (int i=0; i<args.length; i++) {
            if(i==0){
                System.setProperty("apollo.meta", args[i].trim());
            } else if (i==1){
                System.setProperty("app.id", args[i].trim());
            } else if (i==2){
                namespace = args[i].trim();
                System.setProperty("namespace", namespace);
            } else if (i==3){
                System.setProperty("cluster", args[i].trim());
            } else if (i==4){
                System.setProperty("env", args[i].trim());
            }  else if (i==5){
                System.setProperty("apollo.cacheDir", args[i].trim());
            }  else {
                System.out.println("多余参数:"+args[i] + "\t");
            }

        }

        return namespace;
    }





}
